package controller

import (
	"github.com/gin-gonic/gin"
	"log"
	"myserver/model"
	"myserver/param"
	"myserver/response"
	"myserver/service"
)

type HouseController struct {
}

var houseService = service.HouseService{}

func (c *HouseController) Router(apiGroup *gin.RouterGroup) {
	apiGroup.GET("/house", c.gets)
	apiGroup.GET("/houses", c.getHouses)
	apiGroup.POST("/house", c.posts)
	apiGroup.DELETE("/house", c.deletes)
	apiGroup.PUT("/house", c.puts)
}

func (c *HouseController) gets(context *gin.Context) {
	var house model.House
	err := context.ShouldBind(&house)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := houseService.GetHouse(house)
	if res.ID != 0 {
		response.Success(context, response.Ok().AddData("house", res))
	} else {
		response.Failed(context, response.Error().AddData("house", res))
	}
}

func (c *HouseController) posts(context *gin.Context) {
	var house model.House
	err := context.ShouldBindJSON(&house)
	if err != nil {
		log.Println("err = ", err)
	}
	res := houseService.CreateHouse(house)
	if res != 0 {
		response.Success(context, response.Ok())
	} else {
		response.Failed(context, response.Error())
	}
}

func (c *HouseController) deletes(context *gin.Context) {
	var house model.House
	err := context.ShouldBind(&house)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := houseService.DeleteHouse(house)
	if res != 0 {
		response.Success(context, response.Ok())
	} else {
		response.Failed(context, response.Error())
	}
}

func (c *HouseController) puts(context *gin.Context) {
	var house model.House
	err := context.ShouldBind(&house)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := houseService.UpdateHouse(house)
	if res != 0 {
		response.Success(context, response.Ok())
	} else {
		response.Failed(context, response.Error())
	}
}

func (c *HouseController) getHouses(context *gin.Context) {
	var pageParam param.PageParam
	err := context.ShouldBind(&pageParam)
	if err != nil {
		log.Println("err = ", err)
	}
	res := houseService.QueryHouses(pageParam)
	if res.Data != nil && res.Total != 0 {
		response.Success(context, response.Ok().AddData("res", res))
	} else {
		response.Failed(context, response.Error().AddData("res", res))
	}
}
